import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:uuid/uuid.dart';
import 'package:hive/hive.dart';

import '../models/family.dart' as family_model;
import '../models/family_member.dart';

/// 家庭状态提供者
final familyProvider = StateNotifierProvider<FamilyNotifier, family_model.Family?>((ref) {
  return FamilyNotifier();
});

/// 当前选中成员提供者
final selectedMemberProvider = StateProvider<String?>((ref) {
  return null; // null 表示没有选中任何成员
});

/// 家庭状态管理类
class FamilyNotifier extends StateNotifier<family_model.Family?> {
  FamilyNotifier() : super(null) {
    _loadFamily();
  }

  /// 本地存储键
  static const String _storageKey = 'family_data';

  /// 从本地存储加载家庭数据
  Future<void> _loadFamily() async {
    try {
      final box = await Hive.openBox('family_app');
      final familyJson = box.get(_storageKey);
      
      if (familyJson != null) {
        state = family_model.Family.fromJson(Map<String, dynamic>.from(familyJson));
      }
    } catch (e) {
      // 加载失败时使用示例数据（仅用于开发测试）
      _loadSampleData();
    }
  }

  /// 保存家庭数据到本地存储
  Future<void> _saveFamily() async {
    if (state == null) return;
    
    try {
      final box = await Hive.openBox('family_app');
      await box.put(_storageKey, state!.toJson());
    } catch (e) {
      // 保存失败处理
      print('保存家庭数据失败: $e');
    }
  }

  /// 清除家庭数据
  void clearData() {
    state = null;
    
    try {
      Hive.box('family_app').delete(_storageKey);
    } catch (e) {
      print('清除家庭数据失败: $e');
    }
  }

  /// 创建新家庭
  void createFamily({
    required String familyName,
    required String creatorName,
    FamilyRole creatorRole = FamilyRole.admin,
  }) {
    final creator = FamilyMember(
      id: const Uuid().v4(),
      name: creatorName,
      role: creatorRole,
      isCurrentUser: true,
    );
    
    state = family_model.Family.create(
      name: familyName,
      creator: creator,
    );
    
    _saveFamily();
  }

  /// 添加家庭成员
  void addMember({
    required String name,
    required FamilyRole role,
    DateTime? birthday,
    String? avatarUrl,
    String? phoneNumber,
    String? email,
  }) {
    if (state == null) return;
    
    final newMember = FamilyMember(
      id: const Uuid().v4(),
      name: name,
      role: role,
      birthday: birthday,
      avatarUrl: avatarUrl,
      phoneNumber: phoneNumber,
      email: email,
    );
    
    state = state!.addMember(newMember);
    _saveFamily();
  }

  /// 通过邀请码添加成员
  void addMemberByInvite({
    required String name,
    required FamilyRole role,
    DateTime? birthday,
    String? avatarUrl,
  }) {
    addMember(
      name: name,
      role: role,
      birthday: birthday,
      avatarUrl: avatarUrl,
    );
  }

  /// 移除家庭成员
  void removeMember(String memberId) {
    if (state == null) return;
    
    state = state!.removeMember(memberId);
    _saveFamily();
  }

  /// 更新家庭成员
  void updateMember(FamilyMember updatedMember) {
    if (state == null) return;
    
    state = state!.updateMember(updatedMember);
    _saveFamily();
  }

  /// 更新家庭成员心情
  void updateMemberMood(String memberId, MoodStatus mood) {
    if (state == null) return;
    
    state = state!.updateMemberMood(memberId, mood);
    _saveFamily();
  }

  /// 更新当前用户心情
  void updateCurrentUserMood(MoodStatus mood) {
    if (state == null || state!.currentUser == null) return;
    
    updateMemberMood(state!.currentUser!.id, mood);
  }

  /// 更新家庭信息
  void updateFamilyInfo(String name) {
    if (state == null) return;
    
    state = state!.copyWith(name: name);
    _saveFamily();
  }

  /// 重新生成邀请码
  void regenerateInviteCode() {
    if (state == null) return;
    
    state = state!.regenerateInviteCode();
    _saveFamily();
  }

  /// 加载示例数据（仅用于开发测试）
  void _loadSampleData() {
    final creator = FamilyMember(
      id: const Uuid().v4(),
      name: '张爸爸',
      role: FamilyRole.father,
      birthday: DateTime(1980, 5, 15),
      mood: MoodStatus.happy,
      moodUpdatedAt: DateTime.now(),
      isCurrentUser: true,
    );
    
    final family = family_model.Family.create(
      name: '张家',
      creator: creator,
    );
    
    // 添加其他家庭成员
    final mother = FamilyMember(
      id: const Uuid().v4(),
      name: '李妈妈',
      role: FamilyRole.mother,
      birthday: DateTime(1982, 8, 20),
      mood: MoodStatus.calm,
      moodUpdatedAt: DateTime.now().subtract(const Duration(hours: 2)),
    );
    
    final son = FamilyMember(
      id: const Uuid().v4(),
      name: '张小明',
      role: FamilyRole.son,
      birthday: DateTime(2010, 3, 10),
    );
    
    final daughter = FamilyMember(
      id: const Uuid().v4(),
      name: '张小红',
      role: FamilyRole.daughter,
      birthday: DateTime(2015, 11, 5),
    );
    
    final grandfather = FamilyMember(
      id: const Uuid().v4(),
      name: '张爷爷',
      role: FamilyRole.grandfather,
      birthday: DateTime(1955, 1, 1),
      mood: MoodStatus.tired,
      moodUpdatedAt: DateTime.now().subtract(const Duration(days: 1)),
    );
    
    state = family
        .addMember(mother)
        .addMember(son)
        .addMember(daughter)
        .addMember(grandfather);
  }
}
